package com.epro.dx.activity.myaddress;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.adapter.AddressAdapter;
import com.epro.dx.listenner.OnAddressToChangeListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.AddressModel;
import com.weipu.common.facade.model.AddressModel.Address;
import com.weipu.common.facade.model.CountryModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

public class MyAddressBookActivity extends BaseFragmentActivity implements
		OnRefreshListener2<ListView>, OnItemClickListener,
		OnAddressToChangeListenner, OnClickListener {
	private static final String TAG = "MyAddressBookActivity";
	private PullToRefreshListView addressListview;
	private Button addBtn;
	private List<AddressModel> addressModels = new ArrayList<AddressModel>();
	private AddressAdapter addressAdapter;
	private int pageIndex = 1;

	private boolean isChooseAddress;

//	private LinearLayout loadingLayout;

	/**
	 * 获取国家吗
	 */
	private CountryModel countryModel;

	private List<AddressModel> models;

//	private LinearLayout emptyLayout;

//	private ImageView noDataIcon;
//
//	private TextView noDataSuggest;

	private Handler refreshHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			addressAdapter.notifyDataSetChanged();
		};
	};
	private Tracker tracker;
	private Intent intent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//集成GA
		tracker = ((DXApplication)getApplication()).getTracker(TrackerName.APP_TRACKER);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_my_address_book);
		setTitleContent(R.string.my_address_book);
		setLeftBtnContent(true, -1);
		intent = getIntent();
		isChooseAddress = intent.getBooleanExtra("fromChooseAdd", false);
		if(isChooseAddress){
			setTitleContent(R.string.address_choose_title);
		}
		intView();
		setListenner();
		AsyncTaskUtil.executeTask(new LoadingUserAddress(pageIndex, false));
	}

	@Override
	protected void onResume() {
		super.onResume();
		tracker.setScreenName("MyAddressBook");
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		tracker.setScreenName(null);
	}
	
	private void intView() {
		addBtn = (Button) findViewById(R.id.adress_add_btn);
		addressListview = (PullToRefreshListView) findViewById(R.id.my_address_listview);
		addressAdapter = new AddressAdapter(getApplicationContext(),
				addressModels, MyAddressBookActivity.this, addressListview,
				isChooseAddress);
		if(isChooseAddress){
			addressAdapter.setChoosedAddressID(intent.getLongExtra("ChooseAddressID", -1l));
		}
		addressListview.setAdapter(addressAdapter);
	}

	private void setListenner() {
		addressListview.setScrollingWhileRefreshingEnabled(true);
		addressListview.setOnRefreshListener(this);
		addBtn.setOnClickListener(this);
		if (isChooseAddress) {
			addressListview.setOnItemClickListener(this);
		}
	}

	/**
	 * 删除用户收货地址
	 * 
	 * @author hf
	 * @version [版本号, 2015-8-4]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	class DeleteUserAddress extends BaseNeedReLoginTask {
		private long addressId;
		private int position;

		public DeleteUserAddress(long addressId, int position) {
			this.addressId = addressId;
			this.position = position;
		}

		@Override
		protected void onPreExecute() {
//			showWaitingDialog();
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				ProviderFactory.createUserServiceProvider().DeleteAddress(
						addressId,ActivityUtil.getCustomerID(),ActivityUtil.getCustomerToken());
			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
				Logger.e("MyAddressAcitity", "DeleteUserAddress ", e);
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
//				hideWaitingDialog();
				hideAllLayout();
				if ("0".equals(result)) {
					if (null != addressModels
							&& addressModels.size() > position) {
						AddressModel am = addressModels.get(position);
						if (null != am && null != am.getAddress()) {
							if (am.getAddress().getIsDefault() == 1) {
								addressAdapter.setOldPosition(-1);
							}
						}
						addressModels.remove(position);
						if (addressListview.getMode() == Mode.PULL_FROM_START
								&& addressModels.size() == 0) {
							showEmptyLayout(addressListview, R.string.no_address_suggest, R.drawable.sorry);
						}
						addressAdapter.notifyDataSetChanged();
					}

				} else if(!isRelogin){
					AlertToast.alert(MyAddressBookActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
				}
			}
		}

		@Override
		protected Context setContext() {
			return MyAddressBookActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new DeleteUserAddress(addressId, position);
		}
	}

	/**
	 * 设置用户默认收货地址
	 * 
	 * @author hf
	 * @version [版本号, 2015-8-4]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	class SetDefaultUserAddress extends BaseNeedReLoginTask {
		private long addressId;
		private int position;

		public SetDefaultUserAddress(long addressId, int position) {
			this.addressId = addressId;
			this.position = position;
		}

		@Override
		protected void onPreExecute() {
//			showWaitingDialog();
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				for (int i = 0; i < addressModels.size(); i++) {
					AddressModel addressModel = addressModels.get(i);

					if (null != addressModel) {
						Address address = addressModel.getAddress();
						if (position == i) {
							address.setIsDefault(1);
						} else {
							address.setIsDefault(0);
						}
					}
				}
				refreshHandler.sendEmptyMessage(0);
				ProviderFactory.createUserServiceProvider()
						.ChooseDefaultAddress(addressId,ActivityUtil.getCustomerID(),ActivityUtil.getCustomerToken());
			} catch (DxException e) {
				return e.getErrCode();
			} catch (Exception e) {
				Logger.e("MyAddressAcitity", "SetDefaultUserAddress ", e);
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			Logger.i(TAG, "result: " + result);
			super.onPostExecute(result);
			if (!isFinishing()) {
//				hideWaitingDialog();
				hideAllLayout();
				if ("0".equals(result)) {
					if (null != addressModels
							&& addressModels.size() > position) {
						if (position == 0) {
							addressAdapter.notifyDataSetChanged();
							return;
						}
						AddressModel addModel = addressModels.get(position);
						if (null != addModel) {
							addressModels.remove(position);
							addressModels.add(0, addModel);
							addressAdapter.notifyDataSetInvalidated();

						}
					}
				} else if(!isRelogin){
					AlertToast.alert(MyAddressBookActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
				}
			}
		}

		@Override
		protected Context setContext() {
			return MyAddressBookActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new SetDefaultUserAddress(addressId, position);
		}
	}

	private String getUserAddress(boolean isDownRefresh) {
		try {
			String customerid = GlobalConfig.getInstance().getUserSessionCfg()
					.getCustomerid();
			if (null == customerid || "".equals(customerid)) {
				customerid = StringUtil
						.getConfig(
								ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID,
								"0");
			}
			long customerId = Long.parseLong(customerid);
			models = ProviderFactory.createUserServiceProvider().GetAddresses(
					customerId, 1, pageIndex, 10,ActivityUtil.getCustomerToken());
			if (isDownRefresh && models != null) {
				addressModels.clear();
			}
		} catch (DxException e) {
			return e.getErrCode();
		} catch (Exception e) {
			Logger.e("LoginActivity", "LoadingUser", e);
		}
		return "0";

	}

	/**
	 * 获取用户收货地址
	 * 
	 * @author hf
	 * @version [版本号, 2015-8-4]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	class LoadingUserAddress extends BaseNeedReLoginTask {
		private int start;
		private boolean isDownRefresh;

		public LoadingUserAddress(int start, boolean isDownRefresh) {
			this.start = start;
			this.isDownRefresh = isDownRefresh;
		}

		@Override
		protected void onPreExecute() {
			if (start == 1 && !isDownRefresh) {
				showLoadingLayout(null);
			}
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				if (null != BaseFragmentActivity.countryPreferences
						&& !BaseFragmentActivity.countryPreferences.getAll()
								.isEmpty()) {
					countryModel = new CountryModel();
					countryModel
							.setAllCountry(BaseFragmentActivity.countryPreferences
									.getAll());
				} else {
					// FIXME 该部分代码需要优化
					if (null == countryPreferences) {
						countryPreferences = getSharedPreferences(
								"countryData", MODE_PRIVATE);
					}
					countryModel = ProviderFactory.createUserServiceProvider()
							.allCountry();
					BaseFragmentActivity.persistenceCountry(countryModel
							.getAllCountry());
				}
			} catch (DxException e) {
				return getUserAddress(isDownRefresh);
			} catch (Exception e) {
				return getUserAddress(isDownRefresh);
			}
			return getUserAddress(isDownRefresh);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
				if (1 == start) {
					hideAllLayout();
				}
				if ("0".equals(result)) {
					addBtn.setVisibility(View.VISIBLE);
					if (models.size() > 0) {
						addressModels.addAll(models);
						if (1 == start) {
							addressListview.setVisibility(View.VISIBLE);
							addressAdapter = new AddressAdapter(
									getApplicationContext(), addressModels,
									MyAddressBookActivity.this,
									addressListview, isChooseAddress);
							if(isChooseAddress){
								addressAdapter.setChoosedAddressID(intent.getLongExtra("ChooseAddressID", -1l));
							}
							addressListview.setAdapter(addressAdapter);
							addressListview.onRefreshComplete();
						} else {
							addressAdapter.notifyDataSetChanged();
						}
						addressListview.onRefreshComplete();

						// 集合中的数据是否小于列表每次加载数据数量
						if (models.size() < Constant.LIST_PAGE_COUNT) {
							addressListview.setMode(Mode.PULL_FROM_START);
						} else {
							addressListview.setMode(Mode.BOTH);
						}
					} else {
						addressListview.onRefreshComplete();
						if (1 == start) {
							showEmptyLayout(addressListview, R.string.no_address_suggest, R.drawable.sorry);
						} else {
							addressListview.setMode(Mode.PULL_FROM_START);
							addressAdapter.notifyDataSetChanged();
						}
					}
				} else if(!isRelogin){
					// 加载第一页因网络未连接或者超时显示网络异常页面
					if (1 == start
							/*&& (TextUtils
									.equals(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE,
											result)
							
							 * || TextUtils.equals(ServerConstant.ReturnCode.
							 * VALIDATOR_CONNECT_TIMEOUT, result)
							 )*/) {
						if(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)){
							showErrorLayout(addressListview, R.string.internet_error,
									R.string.internet_suggest, R.drawable.no_internet);
						}else{
							showErrorLayout(addressListview, R.string.server_busy,
									R.string.server_suggest, R.drawable.no_internet);
						}
						addBtn.setVisibility(View.GONE);
						retryBtn.setOnClickListener(
								new OnClickListener() {
									@Override
									public void onClick(View v) {
										showLoadingLayout(null);
										AsyncTaskUtil
												.executeTask(new LoadingUserAddress(
														pageIndex, false));
									}
								});
					} else {
						pageIndex--;
						addressListview.onRefreshComplete();
						addressListview.setMode(Mode.BOTH);
						AlertToast.alert(MyAddressBookActivity.this,
								ServerConstant.ReturnCode.MESSAGEMAP
										.get(result));
					}
				}
			}
		}

		@Override
		protected Context setContext() {
			return MyAddressBookActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new LoadingUserAddress(start, isDownRefresh);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		Logger.i(TAG, "onItemClick " + position);
		Intent intent = new Intent();

		AddressModel model = addressModels.get(position - 1);
		String email = StringUtil.getConfig(MyAddressBookActivity.this, ServerConstant.Parameter.PARAMETER_NAME_USER_EMAIL);
		if(!TextUtils.isEmpty(email)){
			model.getAddress().setEmail(email);
		}
		intent.putExtra("addressModel", model);

		setResult(ServerConstant.Parameter.CHOOSE_ADDRESS_CODE, intent);

		finish();
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		pageIndex = 1;
		AsyncTaskUtil.executeTask(new LoadingUserAddress(pageIndex, true));
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		AsyncTaskUtil.executeTask(new LoadingUserAddress(++pageIndex, false));
	}

	@Override
	public void deleteAddress(long addressId, int position) {
		showDeleteDialog(addressId, position);

	}

	@Override
	public void editAddress(AddressModel addressModel, int position) {
		Intent intent = new Intent();
		intent.setClass(getApplicationContext(), EditAddressActivity.class);
		intent.putExtra("from", "editAddress");
		intent.putExtra("countryModel", countryModel);
		intent.putExtra("editModel", addressModel);
		intent.putExtra("position", position);
		// startActivity(intent);
		startActivityForResult(intent,
				ServerConstant.Parameter.EDIT_ADDRESS_CODE);
	}

	@Override
	public void addressCheckStateChange(boolean isCheck, int position) {
		if (null != addressModels) {
			AddressModel addressModel = addressModels.get(position);
			if (null != addressModel) {
				// AddressModel.Address address = addressModel.getAddress();
				// if (null != address) {
				// address.setIsDefault(isCheck ? 1 : 0);
				// }
				if (isCheck) {
					Logger.i(TAG, "position: " + position);
					AsyncTaskUtil.executeTask(new SetDefaultUserAddress(
							addressModel.getAddressID(), position));

				}
			}

		}

	}

	@Override
	public void onClick(View view) {
		Intent intent = new Intent();
		intent.setClass(getApplicationContext(), EditAddressActivity.class);
		intent.putExtra("from", "addAddress");
		intent.putExtra("countryModel", countryModel);
		startActivityForResult(intent,
				ServerConstant.Parameter.ADD_ADDRESS_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (null == data) {
			return;
		}
		AddressModel addressModel = (AddressModel) data
				.getSerializableExtra("addressModel");
		if (requestCode == ServerConstant.Parameter.ADD_ADDRESS_CODE) {

			if (null != addressModel) {
				if (addressListview.getVisibility() != View.VISIBLE) {
					hideAllLayout(addressListview);
				}
				boolean hasDefault = false;
				if (null != addressModels && addressModels.size() > 0) {
					AddressModel am = addressModels.get(0);
					if (null != am) {
						Address address = am.getAddress();
						if (null != address) {
							hasDefault = address.getIsDefault() == 1 ? true
									: false;
						}
					}
				}
				if (hasDefault) {
					addressModels.add(1, addressModel);
				} else {
					addressModels.add(0, addressModel);
				}

				addressAdapter.notifyDataSetInvalidated();
			} else {
				pageIndex = 1;
				AsyncTaskUtil.executeTask(new LoadingUserAddress(pageIndex,
						true));
			}
		}
		if (requestCode == ServerConstant.Parameter.EDIT_ADDRESS_CODE) {
			int editPosition = data.getIntExtra("editPosition", -1);
			if (editPosition != -1 && null != addressModel) {
				if (addressModels.size() > editPosition) {
					addressModels.set(editPosition, addressModel);
					addressAdapter.notifyDataSetChanged();
					// addressModels.get(editPosition).setAddress(
					// addressModel.getAddress());
					// pageAddressModels.get(position).setCountryName(
					// address.getCountryName());
				}
			} else {
				pageIndex = 1;
				AsyncTaskUtil.executeTask(new LoadingUserAddress(pageIndex,
						true));
			}
		}
		super.onActivityResult(requestCode, requestCode, data);
	}

	/**
	 * 删除地址对话框
	 * 
	 * @param cartItem
	 */
	public void showDeleteDialog(final long addressId, final int position) {
		new AlertDialog.Builder(this)
				.setTitle(R.string.delete)
				.setCancelable(true)
				.setMessage(R.string.user_wish_confirm_del)
				.setPositiveButton(R.string.btn_title_ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// new DeleteItem(cartItem).execute();
								AsyncTaskUtil
										.executeTask(new DeleteUserAddress(
												addressId, position));
							}
						})
				.setNegativeButton(R.string.btn_title_cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						}).create().show();
	}

	@Override
	public void reportDefaultAddress(int position) {
		// defaultAddPosition = position;
	}

}
